package com.lishuang.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lishuang.basic.constant.VerifyCodeConstants;
import com.lishuang.basic.exception.BusinessException;
import com.lishuang.basic.jwt.JwtUtils;
import com.lishuang.basic.jwt.LoginData;
import com.lishuang.basic.jwt.RsaUtils;
import com.lishuang.basic.service.impl.BaseServiceImpl;
import com.lishuang.basic.util.AjaxResult;
import com.lishuang.basic.util.HttpUtil;
import com.lishuang.basic.util.MD5Utils;
import com.lishuang.basic.util.StrUtils;
import com.lishuang.system.domain.Menu;
import com.lishuang.user.constant.WxConstants;
import com.lishuang.user.domain.Logininfo;
import com.lishuang.user.domain.User;
import com.lishuang.user.domain.Wxuser;
import com.lishuang.user.dto.BinderDto;
import com.lishuang.user.dto.LoginDto;
import com.lishuang.user.mapper.LogininfoMapper;
import com.lishuang.user.mapper.UserMapper;
import com.lishuang.user.mapper.WxuserMapper;
import com.lishuang.user.service.ILogininfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    /**
     * 账号登录业务
     *
     * @param loginDto
     * @return
     */
    @Override
    public AjaxResult accountLogin(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        Integer loginType = loginDto.getLoginType();

        //1.校验
        //1.1.空值校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(loginType)) {
            throw new BusinessException("数据不能为空");
        }

        //1.2.用户名或密码【加密加盐】校验
        Logininfo logininfo = logininfoMapper.loadByMessage(loginDto);
        if (logininfo == null) {
            throw new BusinessException("用户名或密码错误");
        }
        String md5psd = MD5Utils.encrypByMd5(password + logininfo.getSalt());
        if (!md5psd.equals(logininfo.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }

        //1.3.状态校验 - 启用，禁用
        if (!logininfo.getDisable()) {
            throw new BusinessException("你的账号未激活，请联系管理员!!!");
        }

       /* //2.将token和登录信息对象 保存在 redis 30分钟有效
        String token = UUID.randomUUID().toString();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);

        //3.使用Map将token和登录对象绑定到AjaxResult的resultObj中响应给前端
        //说明：token相当于jessionid   登录对象响应到前端 - 在系统中回显用户名

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        AjaxResult.me().setResultObj(map);*/

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setResultObj(map);
    }

    /**
     * 微信登录业务
     *
     * @param code
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String code) {

        //获取accessToken和openid
        String getAckUrl = WxConstants.GET_ACK_URL
                .replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        String jsonStr = HttpUtil.httpGet(getAckUrl);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid"); //就相当于微信号

        //判断是否已经关联了
        Wxuser wxuser = wxuserMapper.loadByOpenId(openid);


        if (wxuser != null && wxuser.getUserId() != null) {//如果关联了实现免密登录
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());

           /* //将token和登录信息对象 保存在 redis 30分钟有效
            String token = UUID.randomUUID().toString();
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);

            //使用Map将token和登录对象绑定到AjaxResult的resultObj中响应给前端
            //说明：token相当于jessionid   登录对象响应到前端 - 在系统中回显用户名

            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("logininfo", logininfo);*/

            Map<String, Object> map = loginSuccessJwtHandler(logininfo);

            return AjaxResult.me().setResultObj(map);

        } else {//否则跳转到绑定页面
            Map<String, Object> map = new HashMap<>();
            map.put("accessToken", accessToken);
            map.put("openid", openid);

            return AjaxResult.me().setSuccess(false).setResultObj(map);

        }


    }


    /**
     * 微信绑定业务
     *
     * @param binderDto
     * @return
     */
    @Override
    public AjaxResult wechatBinder(BinderDto binderDto) {

        //获取数据
        String phone = binderDto.getPhone();
        String verifyCode = binderDto.getVerifyCode();
        String accessToken = binderDto.getAccessToken();
        String openId = binderDto.getOpenId();

        //空值校验
        if (StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)) {
            throw new BusinessException("数据不能为空!!!");
        }

        //验证码比对
        //获取redis里面的验证码
        Object codeObj = redisTemplate.opsForValue().get(VerifyCodeConstants.BINDER_CODE_PREFIX + phone);
        if (codeObj == null) {//如果为null
            throw new BusinessException("验证码失效。。。");
        } else {//如果不为null
            //获取验证码
            String code = codeObj.toString().split(":")[0];//code：time
            //对比(验证码不同)
            if (!verifyCode.equalsIgnoreCase(code)) {
                throw new BusinessException("验证码错误。。。");
            }
        }

        //获取微信用户信息
        String url = WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String jsonStr = HttpUtil.httpGet(url);

        //微信返回数据转换成Wxuser对象
        Wxuser wxuser = jsonStr2Wxuser(jsonStr); //user_id

        //通过phone查询User
        User user = userMapper.loadByPhone(phone);

        //如果没有 - 根据phone创建User对象 - 创建Logininfo对象 - 保存Logininfo对象 - 保存User对象
        if (user == null) {
            user = phone2User(phone);
            Logininfo logininfoTmp = user2Logininfo(user);
            logininfoMapper.save(logininfoTmp);
            user.setLogininfoId(logininfoTmp.getId());
            userMapper.save(user);
        }

        //将User对象的id设置到WxUser对象中
        wxuser.setUserId(user.getId());

        //将WxUser对象添加到数据库
        wxuserMapper.save(wxuser);

        //做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());

       /* String token = UUID.randomUUID().toString();
        //去掉密码和盐值 - 安全
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);*/

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setResultObj(map);
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        //创建LoginData对象用于等会通过私钥加密
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);
        Map<String, Object> map = new HashMap<>();
        try {
            //1.获取logininfo
            if(logininfo.getType()==0){//管理员
                //2.获取当前登陆人的所有权限 - sn loadPerssionSnByLogininfoId
                List<String> permissions = logininfoMapper.loadPerssionSnByLogininfoId(logininfo.getId());
                //3.获取当前登陆人的所有菜单 - 【难度】
                List<Menu> menus = logininfoMapper.loadMenusByLogininfoId(logininfo.getId());
                loginData.setPermissions(permissions);
                loginData.setMenus(menus);
                //将当前登陆人的权限和菜单添加到map - 响应给前端
                map.put("permissions",permissions);
                map.put("menus",menus);
            }
            //4.通过私钥对登录信息进行加密 - jwtToken串
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader()                                             	  .getResource("auth_rsa.pri").getFile());
            //将登陆人信息加密得到jwtToken串
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30000);
            //5.装到map返回
            map.put("token",jwtToken);
            map.put("logininfo",logininfo);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public void logout(String token) {
        redisTemplate.delete(token);
    }

    /**
     * User对象转换Logininfo对象
     *
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    /**
     * 根据电话号码创建User对象
     *
     * @param phone
     * @return
     */
    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机的纯数据密码
        String randomPwd = StrUtils.getRandomString(6);
        String md5Pwd = MD5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    /**
     * 微信返回数据转换成Wxuser对象
     *
     * @param jsonStr
     * @return
     */
    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }


}

